package com.czd.support.controller;

import com.czd.base.model.JsonResult;
import com.czd.base.model.Paginate;
import com.czd.base.utils.WebUtils;
import com.czd.support.common.Configuration;
import com.czd.support.common.Constants;
import com.czd.support.enums.AuditEnum;
import com.czd.support.enums.Recharge;
import com.czd.support.model.DataDictionary;
import com.czd.support.model.Manager;
import com.czd.support.model.Room;
import com.czd.support.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Author: Jerry.hu
 * Create: Jerry.hu (2014-10-03 22:32)
 * Description:
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/room")
public class RoomController extends BaseController{

    @Autowired
    private RoomService roomService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private RoomUserService roomUserService;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    private HandselHistoryService rechargeHistoryService;
    /**
     *房间分类字典
     * @return
     */
    @ModelAttribute("roomTypeList")
    protected List<DataDictionary> initQuestionType(){
        return dataDictionaryService.queryListByCode(Constants.ROOM_CODE);
    }

    /**
     * 房间类型字典
     * @return
     */
    @ModelAttribute("roomKindList")
    protected List<DataDictionary> initRoomKindList(){
        return dataDictionaryService.queryListByCode(Constants.ROOM_CKIND_ODE);
    }

    /**
     * 房间列表拦截
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = {"","/"},method = RequestMethod.GET)
    public String room(Model model,HttpServletRequest request,Room room,@RequestParam(value = "pageNo",defaultValue = "1") int pageNo){
        Manager manager = this.getSesionUser(request);
        room.setPageNo(pageNo);
        room.setPageSize(Configuration.getInstance().getDefault_page_size());
        int status = WebUtils.findParamInt(request,"status",-1);
        if(manager != null){
            if(status > -1 && status != 3){
                room.setWhere("r.status = "+ status);
            }else{
                room.setWhere(" 1 = 1");
            }
            if(status == 3){
                room.setWhere(room.getWhere() +  " and r.internal = 1");
            }
            Paginate paginate  = roomService.queryForPage(room);
            model.addAttribute("paginate",paginate);
            return "room/list";
        }else{
            return "redirect:/login";
        }
    }

    @RequestMapping(value = "/{id}/details",method = RequestMethod.GET)
    public String details(@PathVariable int id,Model model){
        Room r = new Room();
        r.setId(id);
       Room room = roomService.findOne(r);
       if(room != null){
           model.addAttribute("room",room);
       }
        return "room/details";
    }

    /**
     * 身份认证列表拦截
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = {"/{id}/audit"},method = RequestMethod.POST)
    @ResponseBody
    public JsonResult auditRoom(@PathVariable int id,HttpServletRequest request){
        boolean isAudit = WebUtils.findParamBoolean(request, "isAudit");
        Manager manager = this.getSesionUser(request);
        if(manager != null){
            Room room = new Room();
            room.setId(id);
            room.setUpdatedBy(manager.getUserCode());
            if(isAudit){
                room.setStatus(AuditEnum.审核通过.ordinal());
            }else {
                room.setStatus(AuditEnum.审核未通过.ordinal());
            }
            if(roomService.audit(room)){
                if(isAudit) {
                    Room room1 = roomService.findById(id);
                    int niubi = WebUtils.findParamInt(request, "niubi");
                    rechargeHistoryService.insertAndReturnId(room1.getCreatedBy(), Recharge.赠送.toString(), niubi,manager.getUserCode());
                }
                return JsonResult.OK;
            }else{
                return JsonResult.FAIL.message("审核失败");
            }
        }else{
            return JsonResult.FAIL;
        }
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(){
        return "room/add";
    }

    /**
     * 创建房间
     * @param room
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String save(Room room,HttpServletRequest request,Model model) throws Exception {
        int homeowner = WebUtils.findParamInt(request,"homeowner");
        Manager manager = this.getSesionUser(request);
        room.setUpdatedBy(room.getCreatedBy());
        if(roomService.insert(room) > 0){
            roomUserService.setHomeOwner(room.getId(),homeowner,manager.getUserCode());
            promotionService.insert(room.getId(),manager.getUserCode(),new Integer[]{room.getCreatedBy()});
            return "redirect:/room/"+room.getId()+"/details";
        }
        model.addAttribute("msg","创建失败");
        return "room/add";
    }

    /**
     * 设置房间开启和关闭功能
     * @param roomId
     * @param enable
     * @param request
     * @return
     */
    @RequestMapping(value = "/{roomId}/setEnable/{enable}")
    @ResponseBody
    public JsonResult setEnable(@PathVariable int roomId,@PathVariable int enable,HttpServletRequest request){
        Manager manager = this.getSesionUser(request);
        Room room = new Room();
        room.setId(roomId);
        room.setEnable(enable == 1);
        room.setUpdatedBy(manager.getUserCode());
        if(roomService.setEnable(room)){
            return JsonResult.OK;
        }
        return JsonResult.FAIL;
    }

    /**
     * 设置/取消推广房间
     * @param roomId
     * @param internal
     * @param request
     * @return
     */
	@RequestMapping(value = "/{roomId}/setInternal/{internal}")
	@ResponseBody
	public JsonResult setInternal(@PathVariable int roomId,@PathVariable int internal,HttpServletRequest request){
		Manager manager = this.getSesionUser(request);
		Room room = new Room();
		room.setId(roomId);
		room.setInternal(internal == 1);
		room.setUpdatedBy(manager.getUserCode());
		if(roomService.setInternal(room)){
			return JsonResult.OK;
		}
		return JsonResult.FAIL;
	}

    /**
     * 根据名字查询房间信息
     * @param roomName
     * @return
     */
    @RequestMapping(value = "/findByName", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult findByName(@RequestParam(required = false, value = "roomName", defaultValue = "") String roomName) {
        Room room = roomService.findByName(roomName);
        if (room != null) {
            return new JsonResult(JsonResult.STATUS.OK).put("room", room);
        }
        return JsonResult.FAIL;
    }

}
